package com.zhuangjie.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaungjie.base.conduit.TypeR;
import com.zhuangjie.order.vo.ShopProfitForShopOrderAccountingVO;
import com.zhuangjie.shop.constant.ShopOrderEarliestArrivalTimeConstant;
import com.zhuangjie.shop.entity.ShopMoneyRecord;
import com.zhuangjie.shop.entity.ShopOrderAccountingRecord;
import com.zhuangjie.base.enums.MoneyRecordStatus;
import com.zhuangjie.shop.feign.OrderFeignService;
import com.zhuangjie.shop.mapper.ShopOrderAccountingRecordMapper;
import com.zhuangjie.shop.service.ShopMoneyRecordService;
import com.zhuangjie.shop.service.ShopOrderAccountingRecordService;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.transaction.Propagation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 店铺订单入账记录表 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2024-04-02
 */
@Service
public class ShopOrderAccountingRecordServiceImpl extends ServiceImpl<ShopOrderAccountingRecordMapper, ShopOrderAccountingRecord> implements ShopOrderAccountingRecordService {

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private ShopMoneyRecordService shopMoneyRecordService;

    @Override
    @GlobalTransactional(propagation = Propagation.REQUIRED)
    public void createOrderAccounting(Long orderId) throws Exception {
        // 获取订单是否已经完成，并且返回订单店铺的纯利润用来准备入账
        ShopProfitForShopOrderAccountingVO shopProfitForShopOrderAccountingVO =  TypeR.extract(orderFeignService.queryShopOrderProfitForAccounting(orderId));

        // 插入shop_money_record
        ShopMoneyRecord shopMoneyRecord = new ShopMoneyRecord();
        shopMoneyRecord.setShopId(shopProfitForShopOrderAccountingVO.getShopId());
        shopMoneyRecord.setOperationAmount(shopProfitForShopOrderAccountingVO.getOrderShopProfit());
        shopMoneyRecord.setStatus(MoneyRecordStatus.WAITING_FOR_ENTRY.getCode());
        shopMoneyRecord.setSourceDescribe("店铺订单利润入账");
        shopMoneyRecord.setEarliestArrivalTime(ShopOrderEarliestArrivalTimeConstant.get());
        shopMoneyRecordService.save(shopMoneyRecord);

        // 插入shop_order_accounting_record记录
        ShopOrderAccountingRecord shopOrderAccountingRecord = new ShopOrderAccountingRecord();
        shopOrderAccountingRecord.setOrderId(orderId);
        shopOrderAccountingRecord.setMoneyRecordId(shopMoneyRecord.getId());
        this.save(shopOrderAccountingRecord);

    }
}
